﻿import time
import os
from loguru import logger
from pyautogui import FailSafeException
from gui.ydt_gui import YdtGui
from gui.yima_gui import YimaGui
from gui.ymiot_gui import YmiotGui
from gui.yun_gui import YunGui
from gui.gui_base import GuiBase
import myutils.window_helper as window_helper
from typing import List
from myutils import services_helper
from model.token import TokenType
from myutils import wechat_notify
from model.exception import (
    ParkTokenFatalError,
    ParkTokenFindImageError,
    ParkTokenWechatHwndError,
    ParkTokenTokenParseError,
)
import cv2
import socket
import pyautogui

logger.add(
    sink="./logs/{time:YYYY-MM-DD}.log",
    # format = "{time:HH:mm:ss} {level} {message}",
    level="INFO",
    rotation="00:00",
)


def build_gui_list(config) -> List[GuiBase]:
    """初始化环境"""

    logger.info("检查环境中...")
    fiddler_hwnd = window_helper.find_window_hwnd_first(
        "Progress Telerik Fiddler Classic"
    )
    if not fiddler_hwnd:
        raise ParkTokenFatalError("未找到fiddler窗口")
    else:
        logger.success("找到fiddler窗口")

    wechat_hwnd_list = window_helper.find_window_hwnd_list_by_title("微信")

    wechat_hwnd_list = [
        hwnd for hwnd in wechat_hwnd_list if window_helper.is_valid_wechat_window(hwnd)
    ]

    if not wechat_hwnd_list:
        raise ParkTokenFatalError("未找到微信窗口")
    else:
        logger.info(f"初始化环境:找到{len(wechat_hwnd_list)}个微信窗口")

    gui_list = []

    gui = YdtGui()
    gui.set_wechat_hwnd_list(wechat_hwnd_list)
    gui.set_fiddler_hwnd(fiddler_hwnd)
    gui_list.append(gui)

    if not gui_list:
        raise FailSafeException("无可用的GUI,请检查配置文件")

    return gui_list


def start_gui(gui, retry=0):
    try:
        gui.start()
        return True
    except (FailSafeException, ParkTokenFatalError) as e:
        logger.exception(e)
        raise e
    except ParkTokenWechatHwndError as e:
        logger.exception(e)
    except (ParkTokenFindImageError, ParkTokenTokenParseError) as e:
        logger.exception(e)
        if retry < 5:
            logger.error(f"运行出错,第{retry+1}次重试:{repr(e)}")
            start_gui(gui, retry + 1)
        else:
            raise e

    return False


def notify(msg, config, mention_all=False):
    for url in config["notify_list"]:
        wechat_notify.send(url, f"{socket.gethostname()}:{msg}", mention_all)


if __name__ == "__main__":
    try:
        time.sleep(1)
        round = 0
        while True:
            config = services_helper.get_config()
            logger.info(f"获取到配置: {config}")
            start_time = time.time()
            logger.info(f"第{round + 1}轮开始")
            gui_list = build_gui_list(config)
            success_count = 0
            for gui in gui_list:
                if start_gui(gui):
                    success_count += 1
            total_time = int(time.time() - start_time)
            logger.info(f"第{round + 1}轮结束, 成功{success_count}条, 耗时{total_time}s")
            round += 1
    except Exception as e:
        logger.exception(e)
        notify(f"运行出错:{repr(e)}", config, True)

    os.system("pause")
